package com.example.customizeview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by tangjiangxu on 10/9/17.
 */

public class TestView extends View{

    /** LayoutParams中设置wrap_content时候的大小 **/
    private static final int DEFAULT_WIDHT = 100;
    private static final int DEFAULT_HEIGHT = 100;

    public TestView(Context context) {
        super(context);
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 当自定义的View在布局中设置了wrap_content时，默认效果和match_parent效果一致，这里需要处理
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSepcSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(DEFAULT_WIDHT, DEFAULT_HEIGHT);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(DEFAULT_WIDHT, heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSepcSize, DEFAULT_HEIGHT);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r + 100, b + 100);
    }
}

